<?php
/**
 * GlobalRenderer.php
 * 
 * @category   Naneau
 * @package    Naneau_Plugin
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 * @version    0.2.1
 */

/** base class */
require_once 'Zend/Controller/Plugin/Abstract.php';

/**
 * Naneau_Plugin_View_GlobalRenderer
 * 
 * a very basic plugin to do two-step view, waiting for a decent solution... :x
 * 
 * it gets the content rendered by viewRenderer and sets that as a variable for
 * a global view script. Note the ambiguity between the view in controller
 * context ($this->view) and the view rendered here. They share the same set of
 * variables
 *
 * @category   Naneau
 * @package    Naneau_Plugin
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */
class Naneau_Controller_Plugin_GlobalRenderer extends Zend_Controller_Plugin_Abstract {

    /**
     * global base path for the app
     *
     * @var string
     */
    private $_globalBasePath;

    /**
     * view script to be rendered as appwide
     *
     * @var string
     */
    private $_viewScript;

    /**
     * the view renderer
     *
     * @var Zend_Controller_Action_Helper_ViewRenderer
     */
    private $_viewRenderer;

    /**
     * constructor
     *
     * @param string $globalBasePath the "global" base path for this app
     * @param string $viewScript the view script to render
     */
    public function __construct($globalBasePath = './application/global/views/', $viewScript = 'index.phtml') {
        $this->_globalBasePath = $globalBasePath;
        $this->_viewScript = $viewScript;
        //save settings

        $this->_viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');
        //view renderer action helper

        $this->_viewRenderer->view->addBasePath($this->_globalBasePath);
        //make the view use the global base path
    }

    /**
     * dispatchLoopShutdown hook
     * 
     * runs after all controller actions have finished. Renders the global 
     * template
     * 
     * @return void
     */
    public function dispatchLoopShutdown() {
        if (!$this->_viewRenderer->getNeverRender()) {
            $this->getResponse()->setHeader('content-type', 'text/html; charset=utf-8');
            //a view script can be rendered
            $contents = $this->getResponse()->getBody();
            //the original body, as rendered by the viewRenderer
            $this->_viewRenderer->view->contents = $contents;
            //make the contents available to the view
            $body = $this->_viewRenderer->view->render($this->_viewScript);
            //render the global view script
            $this->getResponse()->setBody($body);
            //update the body from the response
        }
    }
}